/*
 * Copyright 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.windowmanagersample

import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.window.layout.WindowInfoTracker
import androidx.window.layout.WindowMetricsCalculator
import com.example.windowmanagersample.databinding.ActivityWindowMetricsBinding
import com.example.windowmanagersample.infolog.InfoLogAdapter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class WindowMetricsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityWindowMetricsBinding

    private val adapter = InfoLogAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityWindowMetricsBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        binding.recyclerView.adapter = adapter
        adapter.append("onCreate", "triggered")

        logCurrentWindowMetrics("onCreate")

        lifecycleScope.launch(Dispatchers.Main) {
            // The block passed to repeatOnLifecycle is executed when the lifecycle
            // is at least STARTED and is cancelled when the lifecycle is STOPPED.
            // It automatically restarts the block when the lifecycle is STARTED again.
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                // Safely collects from windowInfoRepository when the lifecycle is STARTED
                // and stops collection when the lifecycle is STOPPED.
                WindowInfoTracker.getOrCreate(this@WindowMetricsActivity)
                    .windowLayoutInfo(this@WindowMetricsActivity)
                    .collect { _ ->
                        logCurrentWindowMetrics("折叠状态监听，回调")
                    }
            }
        }
    }

    override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration?) {
        super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig)
        logCurrentWindowMetrics("多窗口状态变化，回调")
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

        val windowCurrentMetrics = WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(this@WindowMetricsActivity)
        val width = windowCurrentMetrics.bounds.width()
        val height = windowCurrentMetrics.bounds.height()

        val windowMaxMetrics = WindowMetricsCalculator.getOrCreate()
            .computeMaximumWindowMetrics(this@WindowMetricsActivity)
        val maxWidth = windowMaxMetrics.bounds.width()
        val maxHeight = windowMaxMetrics.bounds.height()

        val isNotFullWindow = width == maxWidth && height == maxHeight

        logCurrentWindowMetrics("onConfigurationChanged")
    }

    @SuppressLint("NotifyDataSetChanged", "NewApi")
    private fun logCurrentWindowMetrics(tag: String) {
        val windowMetrics = WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(this@WindowMetricsActivity)

        val width = windowMetrics.bounds.width()
        val height = windowMetrics.bounds.height()
        val windowMaxMetrics = WindowMetricsCalculator.getOrCreate()
            .computeMaximumWindowMetrics(this@WindowMetricsActivity)
        val maxWidth = windowMaxMetrics.bounds.width()
        val maxHeight = windowMaxMetrics.bounds.height()
        adapter.append(
            tag, "CURRENT  width: $width， height: $height \n" +
                    "MAX  width: $maxWidth， height: $maxHeight \n" +
                    "isInMultiWindowMode(多窗口状态): $isInMultiWindowMode"
        )
        runOnUiThread {
            adapter.notifyDataSetChanged()
        }
    }
}
